# -*- coding: UTF-8 -*-
__author__ = 'kennyh'

from twisted.internet import threads
from MysqlSet import *
import time
from datetime import datetime as dt_date_time
from logger import logger
from constant import *
from unpack import *
from pack import *

class Storage(object):
    def __init__(self):

        self.saveData_record_time = dt_date_time.now()
        self.save_db_buffer_dict = {}
        self.save_envmonitor_data_dict = {}
        self.msg_buffer = []  # received messages buffer
        self.update_network_info_list = []
        self.update_lamp_devstatus_list = []
        self.mysqlDb = MysqlDb()
        self.data_decode = UnPackData()
        self.data_encode = PackSendData()

        self.StorageThread = threads.deferToThread(self.storage_thread)

        logger.info("StorageServer init!!!!")

    def storage_thread(self):
        while True:
            current_time = dt_date_time.now()
            try:
                if (current_time - self.saveData_record_time).seconds >= 2:
                    #写入数据到数据库
                    #self.saveDataThread = threads.deferToThread(self.save_data)
                    self.save_data()

            except Exception, e:
                logger.error("UDPServer_main_thread error %s" % str(e))

            time.sleep(1)

    def storage_update_network(self, networkid, csq, snr, protocol=0):
        networkinfo = {}
        if protocol == 3:
            networkinfo = {
                'networkid': networkid,
                'rssi': csq,
                'snr': snr,
            }
        else:
            networkinfo = {
                'networkid': networkid,
                'rssi': csq,
            }
        self.update_network_info_list.append(networkinfo)

    def storage_update_nbiot_deviceid(self, networkid, deviceid):
        networkinfo = {
            'networkid': networkid,
            'deviceid': deviceid,
        }
        self.update_network_info_list.append(networkinfo)

    def storage_update_lamp_devstatus(self, lampid, status):

        lampinfo = {
            'lampid': lampid,
            'devstatus': status
        }

        self.update_lamp_devstatus_list.append(lampinfo)

    def save_data(self):
        try:
            if self.save_db_buffer_dict:
                current_result_buffer = []
                save_db_keys = self.save_db_buffer_dict.keys()
                for savekey in save_db_keys:
                    current_result_buffer.append(self.save_db_buffer_dict[savekey])
                    del self.save_db_buffer_dict[savekey]

                self.mysqlDb.insertMany(current_result_buffer)

            if self.save_envmonitor_data_dict:
                current_result_buffer = []
                save_env_keys = self.save_envmonitor_data_dict.keys()
                for savekey in save_env_keys:
                    current_result_buffer.append(self.save_envmonitor_data_dict[savekey])
                    del self.save_envmonitor_data_dict[savekey]

                self.mysqlDb.save_env_monitor_log(current_result_buffer)

            csqlist = [msg for msg in self.update_network_info_list]
            devstatuslist = [msg for msg in self.update_lamp_devstatus_list]
            del self.update_network_info_list[:]
            del self.update_lamp_devstatus_list[:]
            self.mysqlDb.update_network_status(csqlist)
            self.mysqlDb.update_lamp_devstatus(devstatuslist)

        except Exception, e:
            logger.error("saveData: %s" % str(e))

        self.saveData_record_time = dt_date_time.now()



